<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Ywrby个人博客网站 - less is more</title><meta name="author" content="Ywrby"><meta name="copyright" content="Ywrby"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Students majoring in CS at SWU">
<meta property="og:type" content="website">
<meta property="og:title" content="Ywrby个人博客网站">
<meta property="og:url" content="http://ywrby.cn/page/12/index.html">
<meta property="og:site_name" content="Ywrby个人博客网站">
<meta property="og:description" content="Students majoring in CS at SWU">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://ywrby.cn/img/ywrby.png">
<meta property="article:author" content="Ywrby">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ywrby.cn/img/ywrby.png"><link rel="shortcut icon" href="/img/title.png"><link rel="canonical" href="http://ywrby.cn/page/12/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Ywrby个人博客网站',
  isPost: false,
  isHome: true,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2021-12-25 18:42:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><link rel="stylesheet" href="/css/background.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Ywrby个人博客网站" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/ywrby.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">127</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">22</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Bilibili</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 追番列表</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://space.bilibili.com/353923033"><i class="fa-fw fas fa-music"></i><span> B站主页</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="page" id="body-wrap"><header class="full_page" id="page-header" style="background-image: url('/img/back.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Ywrby个人博客网站</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Bilibili</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 追番列表</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://space.bilibili.com/353923033"><i class="fa-fw fas fa-music"></i><span> B站主页</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="site-info"><h1 id="site-title">Ywrby个人博客网站</h1><div id="site-subtitle"><span id="subtitle"></span></div><div id="site_social_icons"><a class="social-icon" href="mailto:ywrby0214@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://space.bilibili.com/353923033" target="_blank" title="Bilibili"><i class="fas fa-file-video"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2278431384&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://twitter.com/ywrby1" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="https://www.facebook.com/profile.php?id=100033741068822" target="_blank" title="Facebook"><i class="fab fa-facebook"></i></a></div></div><div id="scroll-down"><i class="fas fa-angle-down scroll-down-effects"></i></div></header><main class="layout" id="content-inner"><div class="recent-posts" id="recent-posts"><div class="recent-post-item"><div class="post_cover left_radius"><a href="/2021/03/03/8-%E5%B9%B6%E5%8F%91%E5%8C%85/" title="8-并发包">     <img class="post_bg" src="/img/68304874_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="8-并发包"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/8-%E5%B9%B6%E5%8F%91%E5%8C%85/" title="8-并发包">8-并发包</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T05:59:18.000Z" title="Created 2021-03-03 13:59:18">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Java/">Java</a></span></div><div class="content">并发包概念在实际开发中不考虑线程安全的情况下，一般不需要做线程安全处理，防止过多的处理导致性能变差
但是开发中有很多业务需要考虑线程安全的相关问题，此时就必须考虑线程安全的处理
Java为很多业务场景提供了性能优异，且线程安全的并发包
ConcurrentHashMap12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364package ConcurrentHashMap;import java.util.HashMap;import java.util.Hashtable;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;public class CHMDemo1 &#123;    //public static Map&lt;String,String&gt; maps=new HashMap&lt;&gt;();  ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/2021/03/03/7-volatile%E5%85%B3%E9%94%AE%E5%AD%97/" title="7-volatile关键字">     <img class="post_bg" src="/img/80857290_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="7-volatile关键字"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/7-volatile%E5%85%B3%E9%94%AE%E5%AD%97/" title="7-volatile关键字">7-volatile关键字</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T05:59:17.000Z" title="Created 2021-03-03 13:59:17">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Java/">Java</a></span></div><div class="content">并发编程下，多线程访问变量的不可见性问题指多个线程访问共享变量，会出现一个线程修改变量的值后，其他线程看不到最新值的情况
代码示例：12345678910111213141516171819202122232425262728293031323334353637package VolatileTest;public class VolatileDemo extends Thread&#123;    private boolean flag=false;    @Override    public void run() &#123;        try &#123;            Thread.sleep(1000);        &#125; catch (InterruptedException e) &#123;            e.printStackTrace();        &#125;        flag=true;        System.out.println(&quot;flag修改成功！&quot;);    &#125;    p ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/2021/03/03/6-%E6%AD%BB%E9%94%81/" title="6-死锁">     <img class="post_bg" src="/img/68304874_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="6-死锁"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/6-%E6%AD%BB%E9%94%81/" title="6-死锁">6-死锁</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T05:59:16.000Z" title="Created 2021-03-03 13:59:16">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Java/">Java</a></span></div><div class="content">死锁死锁代表的是一种情形：多个线程同时被阻塞，它们中的一个或者全部都在等待某个资源被释放。由于线程被无限期阻塞，因此程序不可能正常终止（例如：客户一方占用资金等待货物资源，经销商一方占用货物资源等待资金，双方都占用一种资源，并且都在等待一种资源，这就导致交易流程无法正常进行，也就形成了所谓的“死锁”）
死锁产生的四个必要条件：
互斥使用：即当一个资源被一个一个线程使用（占有）时，别的线程不能使用
不可抢占：资源请求者不能强制从资源占有者手中夺取资源，资源只能由资源占有者主动释放
请求和保持：即当资源请求者在请求其他的资源的同时保持对原有资源的占有
循环等待：即存在一个等待循环队列，P1要P2的资源，P2要P1的资源，这样就形成了一个等待循环

当上述的四个条件都满足时，便形成死锁，当然，死锁的情况下如果打破上述任何一个条件，便可以让死锁消失。开发中应该尽量避免死锁
死锁在代码形式上通常需要锁的嵌套，也就是在锁的内部还有锁
代码实现：必然死锁的案例12345678910111213141516171819202122232425262728293031323334353637383940 ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/2021/03/03/5-%E7%BA%BF%E7%A8%8B%E6%B1%A0/" title="5-线程池">     <img class="post_bg" src="/img/77593329_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="5-线程池"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/5-%E7%BA%BF%E7%A8%8B%E6%B1%A0/" title="5-线程池">5-线程池</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T05:59:15.000Z" title="Created 2021-03-03 13:59:15">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Java/">Java</a></span></div><div class="content">线程池的概念本质就是一个能够容纳多个线程的容器，其中的线程可以反复利用，省去了频繁创建线程对象的操作，无需因为反复创建线程对象而消耗过多资源

工作线程（PoolWorker）表示线程池中的线程，在没有任务时处于等待状态，可以循环的执行任务
任务队列（TaskQueue）用于存放没有处理的任务，提供一种缓冲机制
任务接口（Task）每个任务必须实现的接口，一共工作线程调度任务的执行，它主要规定了任务的入口，任务执行完后的收尾工作，任务的执行状态等等
线程池管理器（ThreadPool）用于创建并管理线程。包括：创建线程池，销毁线程池，添加线程或任务等等
线程池创建线程来执行，而Worker执行完之后，就去队列中取未分配的task，调用task的run方法。通俗的讲就是任务来后就分配一个线程使用，线程处于占用状态，如果任务执行完毕，线程归还于线程池，并且暂处于空闲状态
合理利用线程池的好处降低资源消耗减少了创建和销毁线程的次数，每个工作线程都可以被重复利用，可以执行多个任务
提高响应速度不需要频繁的创建线程，如果有线程可以直接用，不会出现系统僵死
提高线程的可管理性线程池可以约束系统最多 ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/2021/03/03/4-%E7%BA%BF%E7%A8%8B%E9%80%9A%E4%BF%A1%EF%BC%8C%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81/" title="4-线程通信，线程状态">     <img class="post_bg" src="/img/80857290_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="4-线程通信，线程状态"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/4-%E7%BA%BF%E7%A8%8B%E9%80%9A%E4%BF%A1%EF%BC%8C%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81/" title="4-线程通信，线程状态">4-线程通信，线程状态</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T05:59:14.000Z" title="Created 2021-03-03 13:59:14">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Java/">Java</a></span></div><div class="content">线程通信多个线程因为在同一个进程中，所以互相通信比较容易
线程通信的经典模型：生产者与消费者问题生产者负责生成商品，消费者负责消费商品，生产不能过剩（仍有数据未被消费时不能生产），消费不能没有（不能消费还没有生产的数据）
模拟案例：两名消费者拥有一个共享账户，共享资源，三名生产者负责生产资源。
两名消费者去获取资源，资源存在就取出，不存在就等待，唤醒生产者继续生产资源。
生产者生产资源时，发现仍然存在资源就不继续生产，如果没有资源就生产，然后等待，唤醒消费者来消费
注意：
线程通信一定是多个线程操作同一个资源才需要进行通信
线程通信必须先保证线程安全，否则毫无意义，代码也会报错

线程通信的Object提供三种核心方法
wait()方法：让当前线程进入等待状态，此方法必须由锁对象调用
notify()方法：唤醒当前锁对象上等待状态的某个线程，此方法必须由锁对象调用
notifyAll()方法：唤醒当前锁对象上等待状态的全部线程，此方法必须由锁对象调用

代码实现账户类，定义了存钱和取钱的操作123456789101112131415161718192021222324252627282 ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/2021/03/03/3-%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98%EF%BC%8C%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5/" title="3-多线程安全问题，线程同步">     <img class="post_bg" src="/img/83821828_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="3-多线程安全问题，线程同步"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/3-%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98%EF%BC%8C%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5/" title="3-多线程安全问题，线程同步">3-多线程安全问题，线程同步</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T05:59:13.000Z" title="Created 2021-03-03 13:59:13">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Java/">Java</a></span></div><div class="content">线程安全问题指的是多个线程操作同一个共享资源的时候可能会出现的线程安全问题
银行取钱问题多个用户同时操作一个银行账户进行取钱操作，账户内余额为1000元，每个账户同时取出1000元，由于线程执行的随机性就会导致线程安全问题的产生
银行账户类定义账户内容，定义取钱方法1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950package ThreadSafety;//定义账户类public class Account &#123;    private int cardID;    private double Money;    //定义取钱过程，所有操作这个账户的人都会取走账户中的m元钱    public void DrawMoney(int m)&#123;        //判断取钱的用户        String name =Thread.currentThread().getName();        //判断余额是否充足        if(M ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/2021/03/03/2-%E5%A4%9A%E7%BA%BF%E7%A8%8B/" title="2-多线程">     <img class="post_bg" src="/img/67888138_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="2-多线程"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/2-%E5%A4%9A%E7%BA%BF%E7%A8%8B/" title="2-多线程">2-多线程</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T05:59:12.000Z" title="Created 2021-03-03 13:59:12">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Java/">Java</a></span></div><div class="content">多线程概述（并发编程）进程程序是静止的，而运行中的程序就是进程
特征
动态性：进程是运行中的程序，要动态的占用内存，CPU和网络等资源
独立性：进程和进程之间是相互独立的，彼此有自己独立内存区域
并发性：假如CPU是单核，同一时刻内存中只有一个进程在被执行，CPU会依时为每个进程服务，由于切换速度非常快，给我们的感觉就是这些进程在同时执行，这就是并发性

并行：同一时刻同时有多个进程在执行（多核CPU）
线程线程属于进程，一个进程可以包含多个线程，这就是多线程。（线程是进程中的一个独立执行单元）线程的创建开销相对于进程来说比较小，线程也支持并发性
作用
提高程序效率，线程支持并发性，可以有更多机会得到CPU
多线程可以解决很多业务模型
大型高并发技术的核心技术

线程创建方式一：继承Thread类代码实现12345678910111213141516171819202122232425262728293031323334353637383940package ThreadTest;/** 创建线程的方法一：* 1. 直接定义类继承Thread* 2. 重写run()方法* 3. 创建线 ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/2021/03/03/1-%E5%BC%82%E5%B8%B8/" title="1-异常">     <img class="post_bg" src="/img/72124553_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="1-异常"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/1-%E5%BC%82%E5%B8%B8/" title="1-异常">1-异常</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T05:59:11.000Z" title="Created 2021-03-03 13:59:11">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Java/">Java</a></span></div><div class="content">异常的概念异常是程序在“编译”或者“执行”的过程中可能出现的问题
异常应该尽量提前避免，但是无法做到绝对避免，异常的可能情况太多，开发中只能提前干预。
异常一旦出现，如果没有提前避免，程序就会退出JVM虚拟机而终止，开发中异常是需要提前处理的。研究异常，并且避免异常，然后提前处理异常，体现的是程序的安全性，健壮性
Java会为常见的代码异常都设计一个类来代表
Error错误的意思，严重错误Error，无法通过处理的错误，一旦出现，程序员难以进行修改，一般只能重启系统，优化项目。例如：内存崩溃，JVM本身崩溃
Exception异常类，是开发中代码在编译或者执行过程中可能出现的错误，它是需要提前处理的，以便程序更加健壮

编译时异常：继承自Exception的异常或者其子类，编译阶段就会报错，必须程序员进行处理，否则代码编译无法通过
运行时异常，继承自RuntimeException的异常或其子类，编译阶段不报错，运行阶段出现，运行时异常可处理也可不处理

运行时异常常见的运行时异常
数组索引越界异常：ArrayIndexOutOfBoundsException
空指针异常：NullPo ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/2021/03/03/9-Spring%E9%9B%86%E6%88%90web%E7%8E%AF%E5%A2%83/" title="9-Spring集成web环境">     <img class="post_bg" src="/img/72124553_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="9-Spring集成web环境"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/9-Spring%E9%9B%86%E6%88%90web%E7%8E%AF%E5%A2%83/" title="9-Spring集成web环境">9-Spring集成web环境</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T01:47:56.000Z" title="Created 2021-03-03 09:47:56">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Spring/">Spring</a></span></div><div class="content">ApplicationContext应用上下问的获取方式下面是之前一直采用的应用上下问的获取方法
12345678public class UserServlet extends HttpServlet &#123;    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException &#123;        ApplicationContext context=new ClassPathXmlApplicationContext(&quot;applicationContext.xml&quot;);        UserService service= (UserService) context.getBean(&quot;userService&quot;);        service.save();    &#125;&#125;

通过new ClassPathXmlApplicationC ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/2021/03/03/8-Spring%E4%BA%8B%E5%8A%A1%E6%8E%A7%E5%88%B6/" title="8-Spring事务控制">     <img class="post_bg" src="/img/72175872_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="8-Spring事务控制"></a></div><div class="recent-post-info"><a class="article-title" href="/2021/03/03/8-Spring%E4%BA%8B%E5%8A%A1%E6%8E%A7%E5%88%B6/" title="8-Spring事务控制">8-Spring事务控制</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">Created</span><time datetime="2021-03-03T01:47:51.000Z" title="Created 2021-03-03 09:47:51">2021-03-03</time></span><span class="article-meta tags"><span class="article-meta__separator">|</span><i class="fas fa-tag"></i><a class="article-meta__tags" href="/tags/Spring/">Spring</a></span></div><div class="content">Spring事务控制事务概念
概括来讲，事务是一个由有限操作集合组成的逻辑单元。事务操作包含两个目的，数据一致以及操作隔离。数据一致是指事务提交时保证事务内的所有操作都成功完成，并且更改永久生效；事务回滚时，保证能够恢复到事务执行之前的状态。操作隔离则是指多个同时执行的事务之间应该相互独立，互不影响。

事务是一个比较广泛的概念，事务管理资源除了我们熟知的数据库外，还可以包含消息队列、文件系统等。当然，一般来说，我们说的事务单指“数据库事务”。
事务的ACID属性
原子性（Atomicity）：事务作为一个整体被执行，包含在其中的对数据库的操作要么全部被执行，要么都不执行。
一致性（Consistency）：事务应确保数据库的状态从一个一致状态转变为另一个一致状态。一致状态的含义是数据库中的数据应满足完整性约束。
隔离性（Isolation）：多个事务并发执行时，一个事务的执行不应影响其他事务的执行。
持久性（Durability）：已被提交的事务对数据库的修改应该永久保存在数据库中。

编程式事务控制Spring编程式事务控制就是指利用Spring提供的API进行事务控制，通过编写J ...</div></div></div><nav id="pagination"><div class="pagination"><a class="extend prev" rel="prev" href="/page/11/#content-inner"><i class="fas fa-chevron-left fa-fw"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/11/#content-inner">11</a><span class="page-number current">12</span><a class="page-number" href="/page/13/#content-inner">13</a><a class="extend next" rel="next" href="/page/13/#content-inner"><i class="fas fa-chevron-right fa-fw"></i></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/ywrby.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Ywrby</div><div class="author-info__description">Students majoring in CS at SWU</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">127</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">22</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/ywrby"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="mailto:ywrby0214@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://space.bilibili.com/353923033" target="_blank" title="Bilibili"><i class="fas fa-file-video"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2278431384&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://twitter.com/ywrby1" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="https://www.facebook.com/profile.php?id=100033741068822" target="_blank" title="Facebook"><i class="fab fa-facebook"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>Announcement</span></div><div class="announcement_content">Less is more</div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/12/25/22-%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E6%89%A9%E5%85%85%EF%BC%88%E8%A6%86%E7%9B%96%E4%B8%8E%E4%BA%A4%E6%8D%A2%EF%BC%89/" title="22-内存空间扩充（覆盖与交换）"><img src="/img/67888138_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="22-内存空间扩充（覆盖与交换）"/></a><div class="content"><a class="title" href="/2021/12/25/22-%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E6%89%A9%E5%85%85%EF%BC%88%E8%A6%86%E7%9B%96%E4%B8%8E%E4%BA%A4%E6%8D%A2%EF%BC%89/" title="22-内存空间扩充（覆盖与交换）">22-内存空间扩充（覆盖与交换）</a><time datetime="2021-12-25T08:15:49.000Z" title="Created 2021-12-25 16:15:49">2021-12-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/19/21-%E5%86%85%E5%AD%98%E4%B8%8E%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="21-内存与内存管理"><img src="/img/80857290_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="21-内存与内存管理"/></a><div class="content"><a class="title" href="/2021/12/19/21-%E5%86%85%E5%AD%98%E4%B8%8E%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="21-内存与内存管理">21-内存与内存管理</a><time datetime="2021-12-19T09:57:53.000Z" title="Created 2021-12-19 17:57:53">2021-12-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/11/20-%E6%AD%BB%E9%94%81/" title="20-死锁"><img src="/img/81934649_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="20-死锁"/></a><div class="content"><a class="title" href="/2021/12/11/20-%E6%AD%BB%E9%94%81/" title="20-死锁">20-死锁</a><time datetime="2021-12-11T06:20:20.000Z" title="Created 2021-12-11 14:20:20">2021-12-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/11/28/19-%E7%AE%A1%E7%A8%8B/" title="19-管程"><img src="/img/72581222_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="19-管程"/></a><div class="content"><a class="title" href="/2021/11/28/19-%E7%AE%A1%E7%A8%8B/" title="19-管程">19-管程</a><time datetime="2021-11-28T08:39:08.000Z" title="Created 2021-11-28 16:39:08">2021-11-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/11/17/18-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%EF%BC%88%E5%90%B8%E7%83%9F%E8%80%85%EF%BC%8C%E8%AF%BB%E8%80%85-%E5%86%99%E8%80%85%E7%AD%89%EF%BC%89/" title="18-信号量相关问题（吸烟者，读者-写者等）"><img src="/img/73604608_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="18-信号量相关问题（吸烟者，读者-写者等）"/></a><div class="content"><a class="title" href="/2021/11/17/18-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%EF%BC%88%E5%90%B8%E7%83%9F%E8%80%85%EF%BC%8C%E8%AF%BB%E8%80%85-%E5%86%99%E8%80%85%E7%AD%89%EF%BC%89/" title="18-信号量相关问题（吸烟者，读者-写者等）">18-信号量相关问题（吸烟者，读者-写者等）</a><time datetime="2021-11-17T12:08:38.000Z" title="Created 2021-11-17 20:08:38">2021-11-17</time></div></div></div></div><div class="card-widget card-tags"><div class="item-headline"><i class="fas fa-tags"></i><span>Tags</span></div><div class="card-tag-cloud"><a href="/tags/Docker/" style="font-size: 1.18em; color: #999ca1">Docker</a> <a href="/tags/Electron/" style="font-size: 1.1em; color: #999">Electron</a> <a href="/tags/JVM/" style="font-size: 1.1em; color: #999">JVM</a> <a href="/tags/Java/" style="font-size: 1.38em; color: #99a4b4">Java</a> <a href="/tags/JavaScript/" style="font-size: 1.18em; color: #999ca1">JavaScript</a> <a href="/tags/JavaWeb/" style="font-size: 1.5em; color: #99a9bf">JavaWeb</a> <a href="/tags/Lombok/" style="font-size: 1.1em; color: #999">Lombok</a> <a href="/tags/MyBatis/" style="font-size: 1.22em; color: #999ea4">MyBatis</a> <a href="/tags/MySQL/" style="font-size: 1.34em; color: #99a3b0">MySQL</a> <a href="/tags/P2P/" style="font-size: 1.1em; color: #999">P2P</a> <a href="/tags/Spring/" style="font-size: 1.46em; color: #99a7bb">Spring</a> <a href="/tags/SpringBoot/" style="font-size: 1.26em; color: #999fa8">SpringBoot</a> <a href="/tags/SpringMVC/" style="font-size: 1.3em; color: #99a1ac">SpringMVC</a> <a href="/tags/Swagger/" style="font-size: 1.1em; color: #999">Swagger</a> <a href="/tags/Vue/" style="font-size: 1.14em; color: #999b9d">Vue</a> <a href="/tags/Yaml/" style="font-size: 1.1em; color: #999">Yaml</a> <a href="/tags/tio/" style="font-size: 1.1em; color: #999">tio</a> <a href="/tags/%E5%8C%BA%E5%9D%97%E9%93%BE/" style="font-size: 1.14em; color: #999b9d">区块链</a> <a href="/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" style="font-size: 1.42em; color: #99a6b7">操作系统</a> <a href="/tags/%E6%BC%94%E5%8C%96%E5%8D%9A%E5%BC%88/" style="font-size: 1.1em; color: #999">演化博弈</a> <a href="/tags/%E7%AE%97%E6%B3%95/" style="font-size: 1.1em; color: #999">算法</a> <a href="/tags/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C/" style="font-size: 1.3em; color: #99a1ac">计算机网络</a></div></div><div class="card-widget card-archives"><div class="item-headline"><i class="fas fa-archive"></i><span>Archives</span></div><ul class="card-archive-list"><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/12/"><span class="card-archive-list-date">December 2021</span><span class="card-archive-list-count">3</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/11/"><span class="card-archive-list-date">November 2021</span><span class="card-archive-list-count">21</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/09/"><span class="card-archive-list-date">September 2021</span><span class="card-archive-list-count">4</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/07/"><span class="card-archive-list-date">July 2021</span><span class="card-archive-list-count">2</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/06/"><span class="card-archive-list-date">June 2021</span><span class="card-archive-list-count">3</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/05/"><span class="card-archive-list-date">May 2021</span><span class="card-archive-list-count">3</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/04/"><span class="card-archive-list-date">April 2021</span><span class="card-archive-list-count">16</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/03/"><span class="card-archive-list-date">March 2021</span><span class="card-archive-list-count">75</span></a></li></ul></div><div class="card-widget card-webinfo"><div class="item-headline"><i class="fas fa-chart-line"></i><span>Info</span></div><div class="webinfo"><div class="webinfo-item"><div class="item-name">Article :</div><div class="item-count">127</div></div><div class="webinfo-item"><div class="item-name">UV :</div><div class="item-count" id="busuanzi_value_site_uv"></div></div><div class="webinfo-item"><div class="item-name">PV :</div><div class="item-count" id="busuanzi_value_site_pv"></div></div><div class="webinfo-item"><div class="item-name">Last Push :</div><div class="item-count" id="last-push-date" data-lastPushDate="2021-12-25T10:41:59.790Z"></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/img/back.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Ywrby</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">Local search</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>function subtitleType () {
  if (true) { 
    var typed = new Typed("#subtitle", {
      strings: "Less is more".split(","),
      startDelay: 300,
      typeSpeed: 150,
      loop: true,
      backSpeed: 50
    })
  } else {
    document.getElementById("subtitle").innerHTML = 'L'
  }
}

if (true) {
  if (typeof Typed === 'function') {
    subtitleType()
  } else {
    getScript('https://cdn.jsdelivr.net/npm/typed.js/lib/typed.min.js').then(subtitleType)
  }
} else {
  subtitleType()
}</script></div><div class="aplayer no-destroy" data-id="5402995011" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-lrctype=0	data-order="random" data-preload="none" data-autoplay="true" muted></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>